<template>
  <div id="reagentCategorizeDiv">
    <Breadcrumb content="商品分类" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="40">
          <vxe-toolbar perfect ref="toolbarRef">
            <template #buttons>
              <div class="smallToolTitle">试剂分类</div>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findReagentCategorizeList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" transfer placement="bottom">
                <template #default >新建</template>
                <template #dropdowns>
                  <vxe-button type="text" class="button-blue" content="新建根分类" @click="addRootCategorize()"></vxe-button>
                  <vxe-button type="text" class="button-blue" content="新建子分类" @click="appendCategorize()"></vxe-button>
                </template>
              </vxe-button>
            </template>
          </vxe-toolbar>

          <div class="tableBody">
            <vxe-table
              ref="categorizeTableRef"
              class="mytable-scrollbar"
              border
              height="100%"
              align="left"
              :data="categorizeList"
              :loading="showLoading"
              @current-change="clickRowSelect"
              :row-config="{ isCurrent: true, isHover: true }"
              :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }"
              :tree-config="{
                expandAll: true,
                transform: true,
                rowField: 'id',
                parentField: 'parentId'
              }"
              resizable
              show-overflow
            >
              <vxe-column field="categorizeCode" title="编码" tree-node width="120"> </vxe-column>
              <vxe-column field="categorizeName" title="名称" width="200"> </vxe-column>
              <vxe-column field="remark" title="说明"> </vxe-column>
              <vxe-column title="操作" width="90" align="center" fixed="right">
                <template #default="{ row }">
                  <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="deleteCategorize(row)"></vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>

        <Pane size="60">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="基础信息" name="first">
              <div class="saveBtn">
                <vxe-button type="text" class="button-blue" @click="saveCategorize('categorizeFormRef')" icon="vxe-icon-save" content="保存"></vxe-button>
              </div>
              <el-form ref="categorizeFormRef" :model="categorizeForm" :rules="categorizeFormRule" label-width="100px" class="form-input-m" inline-message>
                <el-form-item prop="pname" label="父级分类" v-if="pnameShow">
                  <el-input type="text" v-model="categorizeForm.pname" placeholder="请输入父类名称" disabled></el-input>
                </el-form-item>
                <el-form-item prop="categorizeCode" label="编号">
                  <el-input type="text" v-model="categorizeForm.categorizeCode" placeholder="请输入编号" clearable></el-input>
                </el-form-item>
                <el-form-item prop="categorizeName" label="名称">
                  <el-input type="text" v-model="categorizeForm.categorizeName" placeholder="请输入名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="说明" prop="remark">
                  <el-input v-model="categorizeForm.remark" placeholder="请输入说明" clearable type="textarea" style="width: 560px"></el-input>
                </el-form-item>
                <el-form-item prop="seq" label="排序" class="input-s">
                  <el-input-number v-model="categorizeForm.seq" :min="0" :max="100" label="请输入顺序号"></el-input-number>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';

let showLoading = ref(false); //刷新加载状态
let sltCategorize: any = ref({});
let activeName = ref('first');
let pnameShow = ref(false); //父级分类显示

let searchForm = {
  searchValue: ''
};

// 最左侧 新建/编辑字典分类弹框表单
let categorizeForm = reactive({
  id: null,
  parentId: null,
  categorizeCode: '',
  categorizeName: '',
  pname: '',
  seq: 1,
  remark: ''
});

// 最左侧字典分类弹框表单校验
let categorizeFormRule = {
  categorizeName: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};
let categorizeList: any = reactive([]);

// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  findReagentCategorizeList();
});

function findReagentCategorizeList() {
  showLoading.value = true;

  const url = '/lis/inv/reagentCategorize/findReagentCategorizeList';
  categorizeList.length = 0; //放入数据前清空数据
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { seachValue: searchForm.searchValue } })
    .then((res: any) => {
      categorizeList.push(...res.data);
      showLoading.value = false;
      proxy.$nextTick(() => {
        const $table = proxy.$refs.categorizeTableRef;
        if ($table) {
          $table.setAllRowExpand(true);
          $table.setAllTreeExpand(true);
        }
      });

      const kn = categorizeList.find((k: any) => k.id == sltCategorize.value.id);
      if (isEmpty(kn)) {
        clickRowSelect({ row: categorizeList[0] }); //默认选中第一条数据
      } else {
        clickRowSelect({ row: kn }); //默认选中第一条数据
      }
    })
    .catch((err: any) => {
      showLoading.value = false;
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}

function clickRowSelect({ row }: any) {
  if (isEmpty(row)) {
    sltCategorize.value = {};
  } else {
    (proxy.$refs.categorizeTableRef as any).setCurrentRow(row);
    sltCategorize.value = row;
    setCategorizeForm(row);
  }
}

function addRootCategorize() {
  pnameShow.value = false;
  clearCategorizeForm();
}

function appendCategorize() {
  clearCategorizeForm();
  categorizeForm.parentId = sltCategorize.value.id;
  categorizeForm.pname = sltCategorize.value.categorizeName;
  pnameShow.value = true;
}

function saveCategorize(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const obj = {
      id: categorizeForm.id,
      parentId: categorizeForm.parentId,
      categorizeCode: categorizeForm.categorizeCode,
      categorizeName: categorizeForm.categorizeName,
      remark: categorizeForm.remark,
      seq: categorizeForm.seq
    };
    let url = '';
    // 判断添加和编辑接口
    if (categorizeForm.id) {
      url = '/lis/inv/reagentCategorize/editReagentCategorize';
    } else {
      url = '/lis/inv/reagentCategorize/addReagentCategorize';
    }
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          if (categorizeForm.id) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增成功', VxeNotifyType.success);
          }
          findReagentCategorizeList();
          //showCategorizeDialog.value = false;
          // 清空表单
          clearCategorizeForm();
        } else {
          if (categorizeForm.id) {
            VxeMessage('修改失败', VxeNotifyType.error);
          } else {
            VxeMessage('新增失败', VxeNotifyType.error);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
      });
  });
}

function setCategorizeForm(row: any) {
  categorizeForm.id = row.id;
  categorizeForm.parentId = row.parentId;
  categorizeForm.categorizeCode = row.categorizeCode;
  categorizeForm.categorizeName = row.categorizeName;
  categorizeForm.remark = row.remark;
  categorizeForm.seq = row.seq;
  if (isEmpty(categorizeForm.parentId)) {
    pnameShow.value = false;
  } else {
    categorizeForm.pname = categorizeList.find((a: any) => a.id == row.parentId).categorizeName;

    pnameShow.value = true;
  }
}

function deleteCategorize(row: any) {
  proxy
    .$confirm('确定删除此分类？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/lis/inv/reagentCategorize/deletReagentCategorize';
      proxy.$http
        .post(url, row)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('删除成功', VxeNotifyType.success);
            findReagentCategorizeList();
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          // VxeMessage('删除字典异常', VxeNotifyType.error);
        });
    });
}

function clearCategorizeForm() {
  //pnameShow.value = false;
  categorizeForm.id = null;
  categorizeForm.parentId = null;
  categorizeForm.categorizeCode = '';
  categorizeForm.categorizeName = '';
  categorizeForm.pname = '';
  categorizeForm.remark = '';
  categorizeForm.seq = 1;
}

function tabHandleClick(tab: any) {
  if (tab.props.name == 'second') {
    //labSuppAppRef.value.initPage(reagentForm.id);
  }
}
</script>

<style lang="scss" scoped>
#reagentCategorizeDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          height: calc(100% - 40px);
          padding: 0;
          .el-tab-pane {
            height: 100%;
          }
          #pane-first {
            padding: 15px;
          }
        }
      }
    }
  }
}
</style>
